//
//  ImageOperation.swift
//  photoTool
//
//  Created by kyuubee on 2023/11/28.
//

import UIKit
import WCDBSwift
import Vision
import Photos
class ImageOperation: Operation {
    public var albumName:String!
    private var myExecuting = false
    private var myFinished = false
    
    override var isExecuting: Bool {
        myExecuting
    }
    
    override var isFinished: Bool {
        myFinished
    }
    
    override func start() {
        myExecuting = true
        let lastBili:Double = UserDefaults.standard.object(forKey: "bili") as! Double
        // 从数据查询一条数据
        let currentImageModel:ImageModel? = try! FileTool().getDb().getObject(fromTable: "image",where: ImageModel.Properties.hasContrast == 0 && ImageModel.Properties.groupName == albumName && ImageModel.Properties.bili > lastBili,orderBy: [ImageModel.Properties.bili.order(.ascending)])
        if currentImageModel == nil {
            // 未查询到数据,重置bili为0
            UserDefaults.standard.setValue(0, forKey: "bili")
            UserDefaults.standard.synchronize()
            myExecuting = false
            myFinished = true
            return
        }
        UserDefaults.standard.setValue(currentImageModel?.bili, forKey: "bili")
        UserDefaults.standard.synchronize()
        // 开始操作，将数据状态更改为爬取中
        currentImageModel?.hasContrast = 1
        try! FileTool().getDb().update(table: "image",on: ImageModel.Properties.hasContrast, with: currentImageModel!,where: ImageModel.Properties.identifier == (currentImageModel?.identifier)!)
        // 查询同比例图片数量
        let imageList:[ImageModel] = try! FileTool().getDb().getObjects(fromTable: "image", where: ImageModel.Properties.bili == (currentImageModel?.bili)! && ImageModel.Properties.localIdentifier != (currentImageModel?.localIdentifier)! && ImageModel.Properties.groupName == albumName)
        // 查询同数据已对比数据数量
        let repeatList:[RepeatedModel] = try! FileTool().getDb().getObjects( fromTable: "repeated",where: RepeatedModel.Properties.leftImgId == (currentImageModel?.localIdentifier)! || RepeatedModel.Properties.rightImgId == (currentImageModel?.localIdentifier)!)
        print("当前比例是\(currentImageModel!.bili ?? 0),同比例数量是\(imageList.count),查询出的记录数量是\(repeatList.count)")
        if imageList.count > 0 && imageList.count > repeatList.count {
            for item in imageList {
                // 对比同比例的数据是否有数据
                let conditionOne:Condition = RepeatedModel.Properties.leftImgId == (currentImageModel?.localIdentifier ?? "")! && RepeatedModel.Properties.rightImgId == item.localIdentifier!
                let conditionTwo:Condition = RepeatedModel.Properties.leftImgId == item.localIdentifier! && RepeatedModel.Properties.rightImgId == (currentImageModel?.localIdentifier ?? "")!
                let array:[RepeatedModel] = try! FileTool().getDb().getObjects(fromTable: "repeated",where: conditionOne.asExpression() || conditionTwo.asExpression())
                if array.isEmpty {
                    // 不存在对比记录，做比较并记录
                    var distance = Float(0)
                    // 获取左边图片的图片信息
                    let leftFeatureModel = PhotoSingle.shared.getImageFeature(localIdentifier: currentImageModel!.localIdentifier!)
                    let rightFeatureModel = PhotoSingle.shared.getImageFeature(localIdentifier: item.localIdentifier!)
                    autoreleasepool {
                        do {
                            try leftFeatureModel.feature.computeDistance(&distance, to: rightFeatureModel.feature)
                        } catch let error {
                            print(error.localizedDescription)
                            distance = 100
                        }
                    }
                    let model = RepeatedModel()
                    model.leftImgId = leftFeatureModel.imageId
                    model.rightImgId = item.localIdentifier
                    model.value = distance
                    try! FileTool().getDb().insert(model, intoTable: "repeated")
                    if distance < 3 {
                        item.hasContrast = 2
                        try! FileTool().getDb().update(table: "image", on: ImageModel.Properties.hasContrast, with: item,where: ImageModel.Properties.identifier == item.identifier!)
                    }
                }
            }
            
        }
        // 更新当前的状态为已经爬取
        currentImageModel?.hasContrast = 2
        try! FileTool().getDb().update(table: "image",on: ImageModel.Properties.hasContrast, with: currentImageModel!,where: ImageModel.Properties.identifier == (currentImageModel?.identifier)!)
        myExecuting = false
        myFinished = true
    }
}
